package com.snow.view;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.http.HttpStatus;

/**
 * 接口返回数据类型标准
 *
 * @author by 13119
 */
@Getter
@Setter
@Accessors(chain = true)
@AllArgsConstructor
public class WebResponse<T> implements IWebResponse {

    /**
     * 状态码
     */
    private Integer status;

    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 描述消息
     */
    private String message;

    /**
     * 负载数据
     */
    private T data;

    /**
     * 扩展数据
     */
    private JSONObject ext;

    public WebResponse<T> setExt(String key, Object value) {
        if (this.ext == null) {
            this.ext = new JSONObject();
        }
        this.ext.set(key, value);
        return this;
    }

    public static <T> WebResponse<T> fail(String message) {
        return new WebResponse<>(HttpStatus.BAD_REQUEST.value(), false, message, null, null);
    }

    public static <T> WebResponse<T> fail(Integer status, String message) {
        return new WebResponse<>(status, false, message, null, null);
    }

    public static <T> WebResponse<T> fail(Integer status, String message, T data) {
        return new WebResponse<>(status, false, message, data, null);
    }

    public static <T> WebResponse<T> success() {
        return new WebResponse<>(200, true, "", null, null);
    }

    public static <T> WebResponse<T> success(T data) {
        return new WebResponse<>(200, true, "", data, null);
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }
}
